# 订单管理模块
from django import forms
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.forms.models import model_to_dict
from web.models import Order, PayMethod, Users, Product
from web.apis import tools
import uuid
from datetime import datetime

# 支付方式表单
class PayMethodForm(forms.ModelForm):
    class Meta:
        model = PayMethod
        fields = "__all__"

    def clean_name(self):
        name = self.cleaned_data.get('name')
        if not name:
            raise forms.ValidationError("支付方式名称不能为空")
        if len(name) > 20:
            raise forms.ValidationError("支付方式名称不能超过20个字符")
        return name

# 订单表单
class OrderForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = "__all__"

    def clean_pay_method(self):
        pay_method = self.cleaned_data.get('pay_method')
        if isinstance(pay_method, PayMethod):
            return pay_method
        try:
            return PayMethod.objects.get(id=pay_method)
        except PayMethod.DoesNotExist:
            raise forms.ValidationError("支付方式不存在")

    def clean_total_price(self):
        total_price = self.cleaned_data.get('total_price')
        if total_price <= 0:
            raise forms.ValidationError("订单总价必须大于0")
        return total_price

    def clean_create_user(self):
        create_user = self.cleaned_data.get('create_user')
        if isinstance(create_user, Users):
            return create_user
        try:
            return Users.objects.get(id=create_user)
        except Users.DoesNotExist:
            raise forms.ValidationError("订单创建者不存在")

    def clean_buy_goodsProduct(self):
        product = self.cleaned_data.get('buy_goodsProduct')
        if isinstance(product, Product):
            return product
        try:
            return Product.objects.get(id=product)
        except Product.DoesNotExist:
            raise forms.ValidationError("商品不存在")

# 创建支付方式
@csrf_exempt
def create_pay_method(request):
    if request.method == 'POST':
        form = PayMethodForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                pay_method = form.instance
                pay_method_dict = model_to_dict(pay_method)
                return JsonResponse(tools.ReturnData(code=200, msg='创建支付方式成功', data=pay_method_dict))
            except Exception as e:
                return JsonResponse(tools.ReturnData(code=400, msg=f'创建支付方式失败: {str(e)}'))
        else:
            error_msg = tools.get_first_error(form)
            return JsonResponse(tools.ReturnData(code=400, msg=f' {error_msg}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 获取支付方式列表
@csrf_exempt
def get_pay_method_list(request):
    if request.method == 'GET':
        try:
            pay_methods = PayMethod.objects.all()
            pay_method_list = [model_to_dict(pm) for pm in pay_methods]
            return JsonResponse(tools.ReturnData(code=200, msg='获取支付方式列表成功', data=pay_method_list))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取支付方式列表失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 更新支付方式
@csrf_exempt
def update_pay_method(request, pay_method_id):
    if request.method == 'POST':
        try:
            pay_method = PayMethod.objects.filter(id=pay_method_id).first()
            if not pay_method:
                return JsonResponse(tools.ReturnData(code=400, msg='支付方式不存在'))
            
            form = PayMethodForm(request.POST, instance=pay_method)
            if form.is_valid():
                form.save()
                pay_method_dict = model_to_dict(form.instance)
                return JsonResponse(tools.ReturnData(code=200, msg='更新支付方式成功', data=pay_method_dict))
            else:
                error_msg = tools.get_first_error(form)
                return JsonResponse(tools.ReturnData(code=400, msg=f' {error_msg}'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'更新支付方式失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 删除支付方式
@csrf_exempt
def delete_pay_method(request, pay_method_id):
    if request.method == 'DELETE':
        try:
            pay_method = PayMethod.objects.filter(id=pay_method_id).first()
            if not pay_method:
                return JsonResponse(tools.ReturnData(code=400, msg='支付方式不存在'))
            
            pay_method.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除支付方式成功'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'删除支付方式失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))

# 创建订单
@csrf_exempt
def create_order(request):
    if request.method == 'POST':
        form = OrderForm(request.POST)
        print(request.POST)
        if form.is_valid():
            try:
                
                print("代码执行到这里")
                # 创建订单对象
                order = Order(
                    order_id=form.cleaned_data['order_id'],
                    status=form.cleaned_data['status'],
                    pay_method_id=form.cleaned_data['pay_method'].id,
                    total_price=form.cleaned_data['total_price'],
                    create_user_id=form.cleaned_data['create_user'].id,
                    buy_goodsProduct_id=form.cleaned_data['buy_goodsProduct'].id,
                    remark=form.cleaned_data.get('remark', ''),
                    buy_goodsProduct_number=form.cleaned_data['buy_goodsProduct_number']
                )
                # 创建订单如果是已支付，则更新商品库存
                if order.status == 2:
                    # 获取商品
                    product = Product.objects.filter(id=form.cleaned_data['buy_goodsProduct'].id).first()
                    # 判断商品货架数量是否足够支持购买
                    if product.shelf_number >= form.cleaned_data['buy_goodsProduct_number']:
                        # 更新库存
                        product.stock -= form.cleaned_data['buy_goodsProduct_number']
                        # 货架数量
                        product.shelf_number -= form.cleaned_data['buy_goodsProduct_number']
                        product.save()
                    else:
                        return JsonResponse(tools.ReturnData(code=400, msg='商品货架数量不足'))
                order.save()
                
                order_dict = model_to_dict(order)
                order_dict['create_time'] = order.create_time.strftime('%Y-%m-%d %H:%M:%S')
                order_dict['update_time'] = order.update_time.strftime('%Y-%m-%d %H:%M:%S')

                
               
                return JsonResponse(tools.ReturnData(code=200, msg='创建订单成功', data=order_dict))
            except Exception as e:
                print(e)
                return JsonResponse(tools.ReturnData(code=400, msg=f'创建订单失败: {str(e)}'))
        else:
            print(form.errors)
            error_msg = tools.get_first_error(form)
            return JsonResponse(tools.ReturnData(code=400, msg=f' {error_msg}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 获取订单列表
@csrf_exempt
def get_order_list(request):
    if request.method == 'GET':
        try:
            orders = Order.objects.all()
            order_list = []
            for order in orders:
                order_dict = model_to_dict(order)
                order_dict['create_time'] = order.create_time.strftime('%Y-%m-%d %H:%M:%S')
                order_dict['update_time'] = order.update_time.strftime('%Y-%m-%d %H:%M:%S')
                order_list.append(order_dict)
            return JsonResponse(tools.ReturnData(code=200, msg='获取订单列表成功', data=order_list))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取订单列表失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 获取单个订单
@csrf_exempt
def get_order(request, order_id):
    if request.method == 'GET':
        try:
            order = Order.objects.filter(order_id=order_id).first()
            if not order:
                return JsonResponse(tools.ReturnData(code=400, msg='订单不存在'))
            
            order_dict = model_to_dict(order)
            order_dict['create_time'] = order.create_time.strftime('%Y-%m-%d %H:%M:%S')
            order_dict['update_time'] = order.update_time.strftime('%Y-%m-%d %H:%M:%S')
            return JsonResponse(tools.ReturnData(code=200, msg='获取订单信息成功', data=order_dict))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取订单信息失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 更新订单
@csrf_exempt
def update_order(request, order_id):
    if request.method == 'POST':
        try:
            order = Order.objects.filter(id=order_id).first()
            if not order:
                return JsonResponse(tools.ReturnData(code=400, msg='订单不存在'))
            
            form = OrderForm(request.POST, instance=order)
            if form.is_valid():
                form.save()
                order_dict = model_to_dict(form.instance)
                order_dict['create_time'] = form.instance.create_time.strftime('%Y-%m-%d %H:%M:%S')
                order_dict['update_time'] = form.instance.update_time.strftime('%Y-%m-%d %H:%M:%S')
                return JsonResponse(tools.ReturnData(code=200, msg='更新订单成功', data=order_dict))
            else:
                error_msg = tools.get_first_error(form)
                return JsonResponse(tools.ReturnData(code=400, msg=f' {error_msg}'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'更新订单失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 删除订单
@csrf_exempt
def delete_order(request, order_id):
    if request.method == 'DELETE':
        try:
            order = Order.objects.filter(order_id=order_id).first()
            print(order,order_id)
            if not order:
                return JsonResponse(tools.ReturnData(code=400, msg='订单不存在'))
            
            order.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除订单成功'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'删除订单失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))

# 更新订单状态
@csrf_exempt
def update_order_status(request, order_id):
    if request.method == 'POST':
        try:
            order = Order.objects.filter(id=order_id).first()
            if not order:
                return JsonResponse(tools.ReturnData(code=400, msg='订单不存在'))
            
            status = request.POST.get('status')
            if not status:
                return JsonResponse(tools.ReturnData(code=400, msg='订单状态不能为空'))
            
            try:
                status = int(status)
                if status not in dict(Order.status_choices).keys():
                    return JsonResponse(tools.ReturnData(code=400, msg='无效的订单状态'))
            except ValueError:
                return JsonResponse(tools.ReturnData(code=400, msg='订单状态必须是数字'))
            
            order.status = status
            order.save()
            
            order_dict = model_to_dict(order)
            order_dict['create_time'] = order.create_time.strftime('%Y-%m-%d %H:%M:%S')
            order_dict['update_time'] = order.update_time.strftime('%Y-%m-%d %H:%M:%S')
            return JsonResponse(tools.ReturnData(code=200, msg='更新订单状态成功', data=order_dict))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'更新订单状态失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))